package com.lin.boot.controller.thread;

import com.lin.boot.thread.ToolkitErrorContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: linjiang
 * @date: 2024/11/18
 */
@RestController
public class ThreadController {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(16), new ThreadPoolExecutor.AbortPolicy());

    @RequestMapping("test")
    public void test() {
        ToolkitErrorContext outer = ToolkitErrorContext.instance();
        outer.resource(Thread.currentThread().getName());

        CompletableFuture.runAsync(() -> {
            ToolkitErrorContext instance = ToolkitErrorContext.instance();
            instance.resource(Thread.currentThread().getName() + "CompletableFuture");
            int i = 1 / 0;
            System.out.println(111);
        }, executor).exceptionally(e -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
            ToolkitErrorContext instance = ToolkitErrorContext.instance();
            System.out.println(instance + "exceptionally");
            return null;
        }).whenComplete((v, e) -> {
            System.out.println(ToolkitErrorContext.instance() + "whenComplete");
            ToolkitErrorContext.clear();
            System.out.println(ToolkitErrorContext.instance());
        });

        System.out.println(outer);
    }
}
